/**
 * 文件浏览器页面逻辑
 */

const { ipcRenderer } = require('electron');
const log = require('electron-log');
const io = require('socket.io-client');
const path = require('path');
const ftpClient = require('../ftpClient');
const {
  SERVER_URL,
  showNotification,
  formatFileSize,
  formatSpeed,
  formatDate,
  getFileIcon,
  getUserData,
  clearUserData,
  setupWindowControls,
  navigateToPage,
  request
} = require('../utils/common');

// ============ 全局变量 ============
let socket = null;
let userData = null;
let currentLocalPath = '';
let currentRemotePath = '/';
let transferTasks = new Map();
let startTime = Date.now();

// ============ DOM元素 - 将在页面加载后获取 ============
let siteStatusInput, hostDisplayInput, userDisplayInput;
let statusIndicator, statusText;

// ============ 页面初始化 ============
window.addEventListener('DOMContentLoaded', async () => {
  console.log('主页面加载中...');
  
  // 检查登录状态
  userData = getUserData();
  console.log('用户数据:', userData);
  
  if (!userData) {
    console.log('未登录，跳转到登录页');
    navigateToPage('login');
    return;
  }
  
  console.log('用户已登录:', userData.user.username);

  // 获取DOM元素
  siteStatusInput = document.getElementById('site-status');
  hostDisplayInput = document.getElementById('host-display');
  userDisplayInput = document.getElementById('user-display');
  statusIndicator = document.getElementById('status-indicator');
  statusText = document.getElementById('status-text');
  
  // 验证关键DOM元素
  if (!siteStatusInput || !userDisplayInput) {
    console.error('关键DOM元素未找到！');
    return;
  }
  
  console.log('DOM元素加载成功');

  // 设置窗口控制
  setupWindowControls();

  // 显示用户信息
  if (userDisplayInput) {
    userDisplayInput.value = userData.user.username;
  }

  // 绑定事件
  bindEvents();

  // 连接WebSocket
  connectWebSocket();

  // 初始化FTP
  await initializeFTP();

  // 加载文件
  await initializeFiles();

  // 启动运行时间计时器
  startRuntimeTimer();

  log.info('文件浏览器页面初始化完成');
});

// ============ 事件绑定 ============
function bindEvents() {
  // 工具栏按钮
  document.getElementById('refresh-btn')?.addEventListener('click', refreshFiles);
  document.getElementById('upload-btn')?.addEventListener('click', selectAndUploadFiles);
  document.getElementById('download-btn')?.addEventListener('click', downloadSelectedFiles);
  document.getElementById('new-folder-btn')?.addEventListener('click', createRemoteFolder);
  document.getElementById('delete-btn')?.addEventListener('click', deleteSelectedFiles);
  document.getElementById('clear-completed-btn')?.addEventListener('click', clearCompletedTasks);
  document.getElementById('open-transfer-page-btn')?.addEventListener('click', () => {
    navigateToPage('transfer');
  });

  // 导航按钮
  document.getElementById('settings-btn')?.addEventListener('click', () => {
    navigateToPage('settings');
  });
  document.getElementById('notifications-btn')?.addEventListener('click', () => {
    navigateToPage('notifications');
  });
  document.getElementById('logout-btn')?.addEventListener('click', performLogout);
}

// ============ FTP初始化 ============
async function initializeFTP() {
  try {
    if (siteStatusInput) siteStatusInput.value = '正在连接...';

    // 设置FTP凭据（使用存储的用户信息）
    ftpClient.setCredentials(
      userData.user.username,
      userData.user.password || '',
      process.env.FTP_HOST || 'drive.kbin.cc',
      parseInt(process.env.FTP_PORT) || 21
    );

    // 连接FTP
    await ftpClient.connect();
    
    if (siteStatusInput) siteStatusInput.value = '已连接';
    updateStatus(true, 'FTP已连接');
    log.info('FTP连接成功');
  } catch (error) {
    log.error('FTP连接失败:', error);
    if (siteStatusInput) siteStatusInput.value = '连接失败';
    updateStatus(false, 'FTP连接失败');
    showNotification('FTP连接失败，但可以使用HTTP传输', 'warning');
  }
}

// ============ 文件初始化 ============
async function initializeFiles() {
  try {
    // 加载本地文件
    currentLocalPath = await ipcRenderer.invoke('get-documents-path');
    await loadLocalFiles(currentLocalPath);
    await renderLocalTree(currentLocalPath);

    // 加载远程文件
    await loadRemoteFiles(currentRemotePath);
    await renderRemoteTree('/');
  } catch (error) {
    log.error('文件初始化失败:', error);
    showNotification('文件加载失败', 'error');
  }
}

// ============ WebSocket连接 ============
function connectWebSocket() {
  socket = io(SERVER_URL, {
    auth: { token: userData.token }
  });

  socket.on('connect', () => {
    log.info('WebSocket连接成功');
    updateStatus(true, 'WebSocket已连接');

    socket.emit('authenticate', {
      userId: userData.user.id,
      username: userData.user.username
    });
  });

  socket.on('authenticated', (data) => {
    if (data.success) {
      log.info('WebSocket认证成功');
    }
  });

  socket.on('disconnect', () => {
    log.warn('WebSocket断开连接');
    updateStatus(false, 'WebSocket断开');

    setTimeout(() => {
      if (socket && !socket.connected) {
        socket.connect();
      }
    }, 5000);
  });

  socket.on('notification', (data) => {
    showNotification(data.content || data.message, data.type || 'info');
  });

  socket.on('transfer:progress', (data) => {
    updateTransferProgress(data.taskId, data.progress, data.speed);
  });

  socket.on('transfer:completed', (data) => {
    markTransferCompleted(data.taskId);
    showNotification(`${data.fileName} 传输完成`, 'success');
    loadRemoteFiles(currentRemotePath);
  });

  socket.on('transfer:failed', (data) => {
    markTransferFailed(data.taskId, data.error);
    showNotification(`${data.fileName} 传输失败`, 'error');
  });
}

// ============ 本地文件操作 ============
async function loadLocalFiles(dirPath) {
  try {
    const files = await ipcRenderer.invoke('read-directory', dirPath);
    currentLocalPath = dirPath;

    const container = document.getElementById('local-files');
    container.innerHTML = '';

    // 添加返回上级目录项
    if (dirPath !== '/') {
      const upItem = createUpItem('local');
      container.appendChild(upItem);
    }

    files.sort((a, b) => {
      if (a.isDirectory && !b.isDirectory) return -1;
      if (!a.isDirectory && b.isDirectory) return 1;
      return a.name.localeCompare(b.name);
    });

    files.forEach(file => {
      const fileItem = createFileItem(file, 'local');
      container.appendChild(fileItem);
    });

    log.info(`加载本地文件: ${dirPath}, 共 ${files.length} 项`);
  } catch (error) {
    log.error('加载本地文件失败:', error);
    showNotification('加载本地文件失败', 'error');
  }
}

async function loadLocalDirs(dirPath) {
  const items = await ipcRenderer.invoke('read-directory', dirPath);
  return items.filter(i => i.isDirectory).map(i => ({ 
    name: i.name, 
    path: i.path, 
    isDirectory: true 
  }));
}

async function renderLocalTree(rootPath) {
  const tree = document.getElementById('local-tree');
  if (!tree) return;
  tree.innerHTML = '';
  const rootNode = { 
    name: rootPath === '/' ? '/' : rootPath.split('/').pop() || rootPath, 
    path: rootPath, 
    isDirectory: true 
  };
  tree.appendChild(createTreeNode(rootNode, loadLocalDirs, (p) => { 
    loadLocalFiles(p); 
  }));
  setTimeout(() => tree.querySelector('.tree-toggle')?.click(), 0);
}

// ============ 远程文件操作 ============
async function loadRemoteFiles(dirPath) {
  try {
    const result = await request(`/api/files?path=${encodeURIComponent(dirPath)}`);

    if (result.success) {
      let files = result.data.files || [];
      currentRemotePath = dirPath;

      // 过滤掉 chunks 文件夹
      const beforeFilter = files.length;
      files = files.filter(file => {
        const fileName = file.name || file.file_name || '';
        return fileName !== 'chunks';
      });
      if (beforeFilter !== files.length) {
        log.info(`已过滤掉 chunks 文件夹，过滤前: ${beforeFilter}, 过滤后: ${files.length}`);
      }

      const container = document.getElementById('remote-files');
      container.innerHTML = '';

      // 添加返回上级目录项
      if (dirPath !== '/') {
        const upItem = createUpItem('remote');
        container.appendChild(upItem);
      }

      files.sort((a, b) => {
        const aIsDir = !!(a.isDirectory || a.type === 'folder');
        const bIsDir = !!(b.isDirectory || b.type === 'folder');
        if (aIsDir && !bIsDir) return -1;
        if (!aIsDir && bIsDir) return 1;
        return a.name.localeCompare(b.name);
      });

      files.forEach(file => {
        const fileItem = createFileItem(file, 'remote');
        container.appendChild(fileItem);
      });

      log.info(`加载远程文件: ${dirPath}, 共 ${files.length} 项`);
    }
  } catch (error) {
    log.error('加载远程文件失败:', error);
    showNotification('加载远程文件失败', 'error');
  }
}

async function loadRemoteDirs(dirPath) {
  const result = await request(`/api/files?path=${encodeURIComponent(dirPath)}`);
  const files = result?.data?.files || [];
  return files
    .filter(f => f.type === 'folder' || f.isDirectory)
    .filter(f => {
      const fileName = f.name || f.file_name || '';
      return fileName !== 'chunks';
    })
    .map(f => ({ 
      name: f.name, 
      path: f.path || f.file_path || `${dirPath}/${f.name}`.replace(/\\/g,'/'), 
      isDirectory: true 
    }));
}

async function renderRemoteTree(rootPath) {
  const tree = document.getElementById('remote-tree');
  if (!tree) return;
  tree.innerHTML = '';
  const rootNode = { name: rootPath, path: rootPath, isDirectory: true };
  tree.appendChild(createTreeNode(rootNode, loadRemoteDirs, (p) => { 
    loadRemoteFiles(p); 
  }));
  setTimeout(() => tree.querySelector('.tree-toggle')?.click(), 0);
}

async function createRemoteFolder() {
  const folderName = prompt('请输入文件夹名称:');
  if (!folderName) return;

  try {
    const result = await request('/api/files/folder', {
      method: 'POST',
      body: JSON.stringify({
        parent_path: currentRemotePath,
        name: folderName
      })
    });

    if (result.success) {
      showNotification('文件夹创建成功', 'success');
      loadRemoteFiles(currentRemotePath);
    } else {
      showNotification(result.message || '创建文件夹失败', 'error');
    }
  } catch (error) {
    log.error('创建文件夹失败:', error);
    showNotification('创建文件夹失败', 'error');
  }
}

// ============ UI辅助函数 ============
function createUpItem(type) {
  const upItem = document.createElement('div');
  upItem.className = 'file-item';
  upItem.innerHTML = `
    <span class="file-item-icon">📁</span>
    <span class="file-item-name">..</span>
    <span class="file-item-size"></span>
    <span class="file-item-date"></span>
  `;
  upItem.addEventListener('dblclick', () => {
    if (type === 'local') {
      const parentPath = path.dirname(currentLocalPath);
      if (parentPath !== currentLocalPath) {
        loadLocalFiles(parentPath);
      }
    } else {
      if (currentRemotePath !== '/') {
        const parentPath = path.dirname(currentRemotePath);
        loadRemoteFiles(parentPath);
      }
    }
  });
  return upItem;
}

function createFileItem(file, type) {
  const item = document.createElement('div');
  item.className = 'file-item';
  item.dataset.path = file.path;
  item.dataset.isDirectory = file.isDirectory || file.type === 'folder';
  item.dataset.type = type;
  item.dataset.id = file.id || '';

  const isFolder = file.isDirectory || file.type === 'folder';
  const icon = isFolder ? '<img src="./assets/Folder.svg" alt="文件夹" style="width: 16px; height: 16px; vertical-align: middle;">' : getFileIcon(file.name);
  const fileSize = isFolder ? '' : formatFileSize(file.size);
  const fileDate = file.modifiedTime ? formatDate(file.modifiedTime) : '';

  item.innerHTML = `
    <span class="file-item-icon">${icon}</span>
    <span class="file-item-name">${file.name}</span>
    <span class="file-item-size">${fileSize}</span>
    <span class="file-item-date">${fileDate}</span>
  `;

  // 双击打开文件夹
  item.addEventListener('dblclick', () => {
    if (isFolder) {
      if (type === 'local') {
        loadLocalFiles(file.path);
      } else {
        loadRemoteFiles(file.path);
      }
    }
  });

  // 单击选中
  item.addEventListener('click', (e) => {
    if (e.ctrlKey || e.metaKey) {
      item.classList.toggle('selected');
    } else {
      const container = item.parentElement;
      container.querySelectorAll('.file-item').forEach(el => el.classList.remove('selected'));
      item.classList.add('selected');
    }
    updateSelectionInfo();
  });

  return item;
}

function createTreeNode(node, loader, onSelect) {
  const container = document.createElement('div');
  container.className = 'tree-node';
  const toggle = document.createElement('span');
  toggle.className = 'tree-toggle';
  toggle.textContent = '▸';
  const label = document.createElement('span');
  label.className = 'tree-label';
  label.textContent = node.name;
  container.appendChild(toggle);
  container.appendChild(label);
  const childrenWrap = document.createElement('div');
  childrenWrap.className = 'tree-children';
  childrenWrap.style.display = 'none';
  let loaded = false;
  
  toggle.addEventListener('click', async (e) => {
    e.stopPropagation();
    if (!loaded) {
      try {
        const children = await loader(node.path);
        childrenWrap.innerHTML = '';
        children.forEach(ch => childrenWrap.appendChild(createTreeNode(ch, loader, onSelect)));
        loaded = true;
      } catch (error) {
        log.error('加载目录树失败:', error);
      }
    }
    const open = childrenWrap.style.display === 'none';
    childrenWrap.style.display = open ? 'block' : 'none';
    toggle.textContent = open ? '▾' : '▸';
  });
  
  label.addEventListener('click', () => onSelect(node.path));
  
  const wrapper = document.createElement('div');
  wrapper.appendChild(container);
  wrapper.appendChild(childrenWrap);
  return wrapper;
}

// ============ 文件上传 ============
async function selectAndUploadFiles() {
  try {
    const filePaths = await ipcRenderer.invoke('open-file-or-folder-dialog');
    if (!filePaths || filePaths.length === 0) return;

    for (const filePath of filePaths) {
      const fileInfo = await ipcRenderer.invoke('get-file-info', filePath);
      
      if (fileInfo.isDirectory) {
        await uploadFolder(filePath);
      } else {
        await uploadFile(filePath);
      }
    }
  } catch (error) {
    log.error('选择文件失败:', error);
    showNotification('选择文件失败', 'error');
  }
}

async function uploadFolder(folderPath) {
  try {
    const folderName = path.basename(folderPath);
    log.info(`开始上传文件夹: ${folderName}`);
    showNotification(`开始上传文件夹: ${folderName}`, 'info');

    const files = await ipcRenderer.invoke('read-directory-recursive', folderPath);
    
    if (files.length === 0) {
      showNotification('文件夹为空', 'warning');
      return;
    }

    for (const file of files) {
      const remotePath = path.join(currentRemotePath, folderName, path.dirname(file.relativePath));
      await uploadFile(file.path, remotePath, file.name);
    }

    showNotification(`文件夹上传完成: ${folderName} (${files.length}个文件)`, 'success');
    loadRemoteFiles(currentRemotePath);
  } catch (error) {
    log.error('上传文件夹失败:', error);
    showNotification('上传文件夹失败', 'error');
  }
}

async function uploadFile(filePath, targetRemotePath = null, customFileName = null) {
  const taskId = `upload-${Date.now()}-${Math.random()}`;

  try {
    const fileInfo = await ipcRenderer.invoke('get-file-info', filePath);
    const fileName = customFileName || path.basename(filePath);
    const remotePath = targetRemotePath || currentRemotePath;

    // 创建传输任务
    const task = {
      id: taskId,
      type: 'upload',
      fileName: fileName,
      filePath: filePath,
      fileSize: fileInfo.size,
      progress: 0,
      speed: 0,
      status: 'uploading',
      startTime: Date.now()
    };
    transferTasks.set(taskId, task);
    addTransferTaskToUI(task);

    // FTP上传
    const ftpRemotePath = path.join(remotePath, fileName).replace(/\\/g, '/');
    log.info(`开始FTP上传: ${filePath} -> ${ftpRemotePath}`);

    const result = await ftpClient.uploadFile(filePath, ftpRemotePath);

    if (result.success) {
      const elapsed = (Date.now() - task.startTime) / 1000;
      const speed = fileInfo.size / elapsed;
      updateTransferProgress(taskId, 100, speed);
      markTransferCompleted(taskId);
      
      if (!targetRemotePath) {
        showNotification(`${fileName} 上传完成`, 'success');
        loadRemoteFiles(currentRemotePath);
      }
    } else {
      throw new Error(result.error || 'FTP上传失败');
    }
  } catch (error) {
    log.error('文件上传失败:', error);
    markTransferFailed(taskId, error.message);
    if (!targetRemotePath) {
      showNotification('文件上传失败', 'error');
    }
  }
}

// ============ 文件下载 ============
async function downloadSelectedFiles() {
  const selectedItems = document.querySelectorAll('#remote-files .file-item.selected');
  if (selectedItems.length === 0) {
    showNotification('请先选择要下载的文件', 'warning');
    return;
  }

  for (const item of selectedItems) {
    if (item.dataset.isDirectory === 'false') {
      await downloadFile(item.dataset.id, item.querySelector('.file-item-name').textContent);
    }
  }
}

async function downloadFile(fileId, fileName) {
  const taskId = `download-${Date.now()}-${Math.random()}`;

  try {
    const savePath = await ipcRenderer.invoke('open-save-dialog', fileName);
    if (!savePath) return;

    const fileInfoResult = await request(`/api/files/${fileId}`);
    
    if (!fileInfoResult.success) {
      throw new Error('获取文件信息失败');
    }

    const fileInfo = fileInfoResult.data;
    const remotePath = fileInfo.file_path;

    const task = {
      id: taskId,
      type: 'download',
      fileName: fileName,
      fileSize: fileInfo.file_size || 0,
      progress: 0,
      speed: 0,
      status: 'downloading',
      startTime: Date.now()
    };
    transferTasks.set(taskId, task);
    addTransferTaskToUI(task);

    log.info(`开始FTP下载: ${remotePath} -> ${savePath}`);
    const result = await ftpClient.downloadFile(remotePath, savePath);

    if (result.success) {
      const elapsed = (Date.now() - task.startTime) / 1000;
      const speed = task.fileSize / elapsed;
      updateTransferProgress(taskId, 100, speed);
      markTransferCompleted(taskId);
      showNotification(`${fileName} 下载完成`, 'success');
    } else {
      throw new Error(result.error || 'FTP下载失败');
    }
  } catch (error) {
    log.error('文件下载失败:', error);
    markTransferFailed(taskId, error.message);
    showNotification('文件下载失败', 'error');
  }
}

// ============ 文件删除 ============
async function deleteSelectedFiles() {
  const selectedItems = document.querySelectorAll('#remote-files .file-item.selected');
  if (selectedItems.length === 0) {
    showNotification('请先选择要删除的文件', 'warning');
    return;
  }

  const fileNames = Array.from(selectedItems).map(item => 
    item.querySelector('.file-item-name').textContent
  );

  if (!confirm(`确定要删除选中的 ${fileNames.length} 个文件吗？\n${fileNames.join('\n')}`)) {
    return;
  }

  for (const item of selectedItems) {
    const fileId = item.dataset.id;
    const fileName = item.querySelector('.file-item-name').textContent;
    
    try {
      const result = await request(`/api/files/${fileId}`, {
        method: 'DELETE'
      });
      
      if (result.success) {
        log.info(`文件删除成功: ${fileName}`);
      } else {
        throw new Error(result.message || '删除失败');
      }
    } catch (error) {
      log.error(`文件删除失败: ${fileName}`, error);
      showNotification(`删除 ${fileName} 失败`, 'error');
    }
  }

  showNotification('文件删除完成', 'success');
  loadRemoteFiles(currentRemotePath);
}

// ============ 传输队列UI ============
function addTransferTaskToUI(task) {
  const container = document.getElementById('transfer-list');
  
  // 清空提示
  const emptyState = container.querySelector('.empty-state');
  if (emptyState) {
    emptyState.remove();
  }

  const taskItem = document.createElement('div');
  taskItem.className = 'transfer-item';
  taskItem.dataset.taskId = task.id;
  
  const typeText = task.type === 'upload' ? '本地 ➜ FTP' : 'FTP ➜ 本地';
  const icon = task.type === 'upload' ? '<img src="./assets/upload.svg" alt="上传" style="width: 16px; height: 16px; vertical-align: middle;">' : '<img src="./assets/dow.svg" alt="下载" style="width: 16px; height: 16px; vertical-align: middle;">';
  
  taskItem.innerHTML = `
    <span class="transfer-icon">${icon}</span>
    <div class="transfer-info">
      <div class="transfer-name">${typeText} ${task.fileName} ${formatFileSize(task.fileSize)}</div>
      <div class="transfer-progress">
        <div class="transfer-progress-bar">
          <div class="transfer-progress-fill" style="width: 0%"></div>
        </div>
        <span class="transfer-status-text">准备传输...</span>
      </div>
    </div>
  `;

  container.appendChild(taskItem);
}

function updateTransferProgress(taskId, progress, speed) {
  const task = transferTasks.get(taskId);
  if (!task) return;

  task.progress = progress;
  task.speed = speed;

  const taskItem = document.querySelector(`[data-task-id="${taskId}"]`);
  if (!taskItem) return;

  const statusText = taskItem.querySelector('.transfer-status-text');
  const progressFill = taskItem.querySelector('.transfer-progress-fill');
  
  if (progressFill) progressFill.style.width = `${progress}%`;
  if (statusText) statusText.textContent = `传输中 ${progress.toFixed(1)}% - ${formatSpeed(speed)}`;
}

function markTransferCompleted(taskId) {
  const task = transferTasks.get(taskId);
  if (!task) return;

  task.status = 'completed';
  task.progress = 100;

  const taskItem = document.querySelector(`[data-task-id="${taskId}"]`);
  if (!taskItem) return;

  const statusText = taskItem.querySelector('.transfer-status-text');
  const progressFill = taskItem.querySelector('.transfer-progress-fill');
  
  if (progressFill) progressFill.style.width = '100%';
  if (statusText) statusText.textContent = '传输完成';
  taskItem.style.opacity = '0.6';
}

function markTransferFailed(taskId, errorMessage) {
  const task = transferTasks.get(taskId);
  if (!task) return;

  task.status = 'failed';
  task.error = errorMessage;

  const taskItem = document.querySelector(`[data-task-id="${taskId}"]`);
  if (!taskItem) return;

  const statusText = taskItem.querySelector('.transfer-status-text');
  const progressFill = taskItem.querySelector('.transfer-progress-fill');
  
  if (progressFill) {
    progressFill.style.width = '100%';
    progressFill.style.background = '#f44336';
  }
  if (statusText) statusText.textContent = `传输失败: ${errorMessage}`;
  taskItem.style.background = '#ffebee';
}

function clearCompletedTasks() {
  transferTasks.forEach((task, taskId) => {
    if (task.status === 'completed') {
      const taskItem = document.querySelector(`[data-task-id="${taskId}"]`);
      if (taskItem) taskItem.remove();
      transferTasks.delete(taskId);
    }
  });

  const container = document.getElementById('transfer-list');
  if (container.children.length === 0) {
    container.innerHTML = '<div class="empty-state">暂无传输任务</div>';
  }
}

// ============ 辅助功能 ============
function refreshFiles() {
  loadLocalFiles(currentLocalPath);
  loadRemoteFiles(currentRemotePath);
  showNotification('已刷新', 'info');
}

function updateSelectionInfo() {
  const selectedItems = document.querySelectorAll('.file-item.selected');
  const selectionInfo = document.getElementById('selection-info');
  if (selectionInfo) {
    selectionInfo.textContent = `选中: ${selectedItems.length} 文件`;
  }
}

function updateStatus(isConnected, message = '') {
  if (statusIndicator) {
    statusIndicator.className = isConnected ? 'status-indicator' : 'status-indicator offline';
  }
  if (statusText && message) {
    statusText.textContent = message;
  }
}

function startRuntimeTimer() {
  const runtimeElement = document.getElementById('runtime');
  if (!runtimeElement) return;

  setInterval(() => {
    const elapsed = Date.now() - startTime;
    const hours = Math.floor(elapsed / 3600000);
    const minutes = Math.floor((elapsed % 3600000) / 60000);
    const seconds = Math.floor((elapsed % 60000) / 1000);
    
    runtimeElement.textContent = `运行时间: ${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
  }, 1000);
}

function performLogout() {
  if (confirm('确定要退出登录吗？')) {
    // 断开连接
    if (socket) {
      socket.disconnect();
    }
    if (ftpClient) {
      ftpClient.disconnect();
    }
    
    // 清除用户数据
    clearUserData();
    
    // 跳转到登录页
    navigateToPage('login');
  }
}
